#pragma once
#include <sys/time.h>
#include <sys/epoll.h>
#include <pthread.h>
#include <netinet/in.h>

#include <map>
#include <string>
#include <deque>

#include "Thread.h"
#include "ThreadPool.h"
#include "Socket.h"
#include "Connect.h"

namespace sevent{

class Server;
class Loop
{
public:
	typedef boost::function <int (Connect *, char*)> TaskFunc;
	Loop(const std::string ip, const int port);
	~Loop();

	int init();
	int start();
	int stop();
	int wait();

	int deleteConnect(int fd);
	int prepareConnect(Connect *c);
	Connect* getConnect(int fd);

	bool started() const {
		return _started;
	}

	int lock();
	int unLock();

	std::string& name();
	
	Server *getServer(){return _server;}
	void setServer(Server *server){_server = server;}

	ThreadPool &getTaskThreadPool();
	ThreadPool &getIOThreadPool();
private:
	Server *_server;

	bool _started;

	pthread_mutex_t _mutex;
	pthread_cond_t _cond;

	ThreadPool _IOThreadPool; //for IO
	int recvMessageTask(Connect *c, char *);
	int sendMessageTask(Connect *c, char *);

	Thread _pollThread; //for epoll Accept
	int pollThreadInit();
	int pollThreadRun();
	int pollThreadStop();

	Address _listenAddr;
	int _listenSock;
	
	int _epfd;
	struct epoll_event _epevents[1024];
	struct epoll_event _eplistenevent;
	
	std::map<int, Connect *> _connectMap; //the fd has been used
	
	int checkTask();
	
	
};


}

